package cn.xjfme.encrypt.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.KeyUtil;
import cn.hutool.crypto.symmetric.SM4;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;

import javax.crypto.KeyGenerator;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.util.UUID;

import static cn.hutool.crypto.Mode.CBC;
import static cn.hutool.crypto.Padding.ZeroPadding;

/**
 * @author zhangjie
 * @since 2023-3-14 09:13:30
 */
public class Sm4EncryptUtil {

    // 128-32位16进制；256-64位16进制
    private static final int DEFAULT_KEY_SIZE = 128;


    public static String encrypt( String accessKey,String plainTxt) {
        SymmetricCrypto sm4 = new SM4(CBC, ZeroPadding,Base64.decode(accessKey), "iviviviviviviviv".getBytes(CharsetUtil.CHARSET_UTF_8));
        byte[] encryptHex = sm4.encrypt(plainTxt);
        return Base64.encode(encryptHex);
    }

    public static String decrypt(String accessKey,String cipherTxt) {
        SymmetricCrypto sm4 = new SM4(CBC, ZeroPadding,Base64.decode(accessKey), "iviviviviviviviv".getBytes(CharsetUtil.CHARSET_UTF_8));
        byte[] cipherHex = Base64.decode(cipherTxt);
        return sm4.decryptStr(cipherHex, CharsetUtil.CHARSET_UTF_8);
    }

    public static void main(String[] argc) {
        String originTxt = "测试";
        System.out.println("原文: " + originTxt);
        String key = generateSm4Key();
        System.out.println(key);
        String cipherTxt = encrypt( key,originTxt);
        System.out.println("密文: " + cipherTxt);
        String plainTxt = decrypt(key,cipherTxt);
        System.out.println("解密结果: " + plainTxt);
    }

    public static String generateSm4Key() {

       return Base64.encode(KeyUtil.generateKey("sm4", DEFAULT_KEY_SIZE).getEncoded());
    }
}